/**
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 * 不要修改和使用这个文件，这个文件专门给财务管理-单据审核-人工核票用的
 */

import { messages, queryCurrencyPrecision, mulCalculate, deepFullCopy, currencyPrecisionCal } from "share/common";
import React from "react";
import { connect } from "react-redux";
import {
  Spin,
  Input,
  DatePicker,
  Row,
  Col,
  Icon,
  Popover,
  Form,
  Select,
  InputNumber,
  Button,
  message,
  Modal,
  Tag,
  Alert,
} from "antd";
import moment from "moment";
import Invoice from "containers/my-account/invoice";
import "styles/my-account/create-invoice.scss";
import expenseService from "containers/my-account/expense.service";
import errorMessage from "share/errorMessage";
import Condition from "components/condition";
import FileUpload from "components/file-upload";
import IeFileUpload from "components/template/ie-file-upload/ie-file-upload";
import ImageUpload from "components/image-upload";
import IeImgUpload from "components/template/ie-file-upload/ie-img-upload";
import InvoiceMoreInfoEdit from "containers/my-account/components/invoice-more-info-edit";
import dataSources from "containers/my-account/data-sources/data-sources";
import myAccountFunction from "./my-account.function";
import { auditSaveReceipt, shouldChangeFeeAutomatic } from "containers/my-account/components/common-method";
import InvoiceGoods from "./components/invoice-goods";
import CommonModal from "../expense/component/common-modal";
import ReceiptCompare from "./components/receipt-compare";

const FormItem = Form.Item;
const { Option } = Select;
const { If, Else } = Condition;

const {
  showUserInfoOptions,
  internalOptions,
  agentTagOptions,
  receiptFieldItemMap,
  domesticPassengersOptions,
} = dataSources;
const { isFieldDisabled, invoiceAttachmentInfo, isCompleteInvoice, shouldCompare } = myAccountFunction;

class CreateInvoice extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      currentStep: 0,
      checking: false,
      warning: "",
      taxRates: [],
      invoiceTypes: [],
      recordTaxRateConfig: false, //补录税率配置，当查验返回R_2002，需要强制显示税率／税额／不含税金额控件。切换发票类型取消。
      recordTaxAmountConfig: false, //补录税率配置，税额合计特殊处理
      additionalRecordingPriceAmountConfig: false, //补录价税合计配置，当查验返回R_2007，需要强制显示价税合计控件。切换发票类型取消。
      recordNonVATinclusiveAmountConfig: false, //补录税率配置,金额合计特殊处理
      receiptConfigList: [], //发票控件配置对象信息
      canSubmit: true,
      resultReceipt: {},
      beforeReceipt: {},
      companyOpenInvoice: false, //公司是否开通了票++
      invoiceOptionsFetching: false,
      receiptTipImages: {}, // 发票提醒图片
      imageIsUploading: false, //发票图片是否正在上传
      bagSaving: false,
      moreInfo: JSON.parse(props.receipt.moreInfo || "{}"),
      invoiceInfo: deepFullCopy(props.receipt), //发票详情
      auditSaving: false,
      showOCRFlag: false, //是否开通OCR
      isAuditCheck: props.pageFrom === "auditCheck", //财务核对发票
      attachmentEditable: false, // 发票附件是否可编辑
      cacheReceiptLabels: this.props.receipt.receiptLabels || [], // 标签信息
      receiptGroup: [], // 发票分组 及多张发票信息
    };
  }

  componentDidMount() {
    this.init();
  }

  init = async () => {
    const { receipt } = this.props;
    this.setState({ loading: true, invoiceOptionsFetching: true });
    const res = await Promise.all([this.getInvoiceType(), this.getTaxRates(), this.getTitleListByEntity()]);
    const [invoiceTypes, taxRates, titleDetail = {}] = res;
    receipt &&
      receipt.invoiceTypeNo &&
      !invoiceTypes.some((item) => item.value === receipt.invoiceTypeNo) &&
      invoiceTypes.push({
        value: receipt.invoiceTypeNo,
        messageKey: receipt.type || receipt.invoiceTypeNo,
        isEnable: false,
        remark: messages("common.disabling") /*已禁用*/,
      });
    invoiceTypes.forEach((item) => {
      if (item.remark) {
        item.messageKey = `${item.messageKey}(${item.remark})`;
      }
    });
    this.setState(
      {
        taxRates,
        invoiceTypes,
        loading: false,
        invoiceOptionsFetching: false,
        showOCRFlag: titleDetail.showOCRFlag,
        companyOpenInvoice: titleDetail.showCheckInvoiceFlag,
      },
      () => this.initReceiptValue(receipt)
    );
  };
  //获取发票抬头，判断公司是否开票++
  getTitleListByEntity = async () => {
    const { user, userOID } = this.props;
    const res = await expenseService.getTitleList(userOID || user.userOID);
    return res.data;
  };
  //获取所有税率
  getTaxRates = async () => {
    let res = { data: [] };
    try {
      res = await expenseService.getRateByInvoiceType("");
      res.data.sort((a, b) => a.taxRateValue > b.taxRateValue || -1);
    } catch (e) {}
    return res.data;
  };

  getInvoiceType = async () => {
    const { ownerOID, userOID, receipt } = this.props;
    this.setState({ invoiceOptionsFetching: true });
    const res = await expenseService.getInvoiceTypeList(ownerOID || userOID);
    return res.data.rows;
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.receipt.id !== this.props.receipt.id) {
      this.initReceiptValue(nextProps.receipt);
    }
  }

  //验证多发票逻辑
  //只在费用详情中创建和编辑发票时需要验证，其余暂时不需要 用pageFrom参数区分了
  //这里传进来的receiptList 在单据审核发票模式下和发票袋审核下为员工发票list 不包括财务扫描的，还有很多时候为空因为暂时不需要，需注意
  validateMoreReceiptList = (invoiceInfo, isValidateRate = false) => {
    const { receiptList, receiptOperateScene, receiptIndex, pageFrom, entryType } = this.props;
    let tip = "";
    if (!(receiptOperateScene === 3 && receiptList.length === 1) && entryType === "new-expense" && pageFrom !== "OCR") {
      receiptList.length > 0 &&
        receiptList.some((item, index) => {
          if (
            !(receiptOperateScene === 3 && index === receiptIndex) &&
            invoiceInfo.invoiceTypeNo === item.invoiceTypeNo
          ) {
            //机票行程单单独验证号码、其他均需要代码号码均有值才验证
            if (String(invoiceInfo.invoiceTypeNo) === "150") {
              if (invoiceInfo.billingNo && invoiceInfo.billingNo === item.billingNo) {
                tip = messages("expense-1.key155") /*当前发票已存在，请勿重复添加*/;
                return true;
              }
            } else if (
              invoiceInfo.billingCode &&
              invoiceInfo.billingNo &&
              invoiceInfo.billingCode === item.billingCode &&
              invoiceInfo.billingNo === item.billingNo
            ) {
              tip = messages("expense-1.key155") /*当前发票已存在，请勿重复添加*/;
              return true;
            }
          }
        });
    }
    return tip;
  };

  //获取发票补录信息
  checkSuccessByCode = (resultCode, isSave) => {
    const { attachmentEditable } = this.state;
    const checkSuccess = isCompleteInvoice(resultCode);
    if (resultCode === "R_2007") {
      this.setState({
        additionalRecordingPriceAmountConfig: true,
      });
    }
    if (resultCode === "R_2008") {
      this.setState({
        additionalRecordingPriceAmountConfig: true,
        recordTaxRateConfig: true,
      });
    }
    if (resultCode === "R_2002") {
      this.setState({
        recordTaxRateConfig: true,
      });
    }
    if (isSave && ["R_2012", "R_2013"].includes(resultCode) && !attachmentEditable) {
      this.setState({ attachmentEditable: true });
    }
    return checkSuccess;
  };
  //发票是否查验成功
  isCheckSuccessfulInvoice = (invoiceInfo) => {
    return invoiceInfo.checkResult === "R_0000";
  };
  /**
   * 判断发票是否可编辑
   * 可编辑场景
   *       1: resultCode为130102（特殊校验码）
   *       2: 查验失败
   *       3: 不可生成费用缺少字段
   */
  isEditableInvoice = (resultCode, invoice, isOk) => {
    if (resultCode === "130102") {
      return true;
    }
    if (isOk === "N") {
      //不可生成费用
      // ocr 查验失败可编辑
      if (!this.isCheckSuccessfulInvoice(invoice)) {
        return true;
      }
      // 信息不全
      return !isCompleteInvoice(resultCode);
    }
    // 或者查验失败即可编辑
    return !this.isCheckSuccessfulInvoice(invoice);
  };
  // 查验发票
  testInvoice = (invoiceInfo) => {
    this.setState({ checking: true });
    const {
      invoiceBagId,
      expenseReportId,
      user,
      userOID,
      fromVICP,
      expenseReportOID,
      ownerOID,
      createType,
    } = this.props;
    let type = createType === 2 && invoiceInfo.entityType === "invoice" ? "invoice" : null;
    if (invoiceBagId) type = "bag";
    if (expenseReportId) type = invoiceInfo.invoiceOID ? "invoice" : "expense_report";
    if (fromVICP) type = "VICP";
    const isFinancialOperateType = createType === 2;
    const isInvoiceFromFinancialEntry = !!type && type !== "invoice";
    expenseService
      .testInvoice(
        invoiceInfo,
        ownerOID || userOID || user.userOID,
        type,
        invoiceBagId || expenseReportId,
        expenseReportOID,
        isFinancialOperateType,
        isInvoiceFromFinancialEntry
      )
      .then((res) => {
        this.setState({ checking: false });
        // const data = type ? res.data : res.data[0];
        const data = res.data;
        const receipt = data.invoiceInfo;
        const tip = this.validateMoreReceiptList(receipt, true);

        if (!this.checkSuccessByCode(data.resultCode, true)) {
          message.info(data.msg);
          return;
        }
        if (!receipt) {
          message.error(data.msg);
          return;
        }

        if (tip) {
          Modal.info({
            title: tip,
          });
          return;
        }

        // 后端自动补全了补录信息
        if (data.resultCode === "R_2010") {
          message.success(data.msg);
        }
        //  需要对比
        if (data.isOk === "N" && shouldCompare(data)) {
          this.setState({ checking: true });
          this.handleCompare(data).finally(() => {
            this.setState({ checking: false });
          });
          return;
        }

        // 如果可编辑 且不可生成费用 则需要提示错误信息
        if (this.isEditableInvoice(data.resultCode, receipt, data.isOk) && data.isOk === "N") {
          const cacheReceiptLabels = data.errorList.map((receipt) => {
            return {
              ...receipt,
              name: receipt.title,
              toast: receipt.message,
              type: receipt.code,
            };
          });
          this.setState({ cacheReceiptLabels });
          try {
            document.querySelector(".expense-type-box").scrollTo(0, 0);
          } catch (e) {}
          return;
        }
        this.handleFinally(data, invoiceInfo);
      })
      .catch((e) => {
        this.setState({ checking: false });
        errorMessage(e.response);
      });
  };

  handleFinally = (data, invoiceInfo) => {
    const { invoiceBagId, expenseReportId, fromVICP, onCreate, receiptOperateScene } = this.props;
    const { showOCRFlag } = this.state;
    let errorList = data.errorList;
    let receipt = data.invoiceInfo;
    // 逻辑修改 200成功就跳转生成费用查看发票
    errorList.length > 0 &&
      errorList.forEach((item) => {
        item.name = item.title;
        item.toast = item.message;
      });
    receipt.receiptLabels = errorList;
    this.setState({ cacheReceiptLabels: [] });
    if (
      +receiptOperateScene === 1 &&
      data.isOk === "Y" &&
      !(this.props.createType === 2 && this.props.currentTab !== "prending_audit")
    ) {
      this.handleReceiptGroup(data, receipt, errorList);
      return;
    }
    if (data.isOk === "Y" && !invoiceBagId && !expenseReportId && !fromVICP) {
      // createType: 2 财务操作类型  1 用户操作类型
      if (this.props.createType === 2 && this.props.currentTab !== "prending_audit") {
        this.auditSave(receipt, true);
        return;
      }
      onCreate ? onCreate(receipt, showOCRFlag) : this.props.close(true);
      return;
    }

    receipt.resultCode = data.resultCode;
    this.setState({
      resultReceipt: receipt,
      beforeReceipt: invoiceInfo,
      currentStep: 1,
      canSubmit: false,
    });
  };

  handleReceiptGroup = (data, receipt, errorList) => {
    // 发票创建费用 且可生成费用 13419 发票分组处理
    const { onCreate } = this.props;
    const { showOCRFlag } = this.state;
    this.setState({ checking: true });
    expenseService
      .getReceiptGroups([receipt], 1001)
      .then((res) => {
        const sourceReceiptGroup = this.safeGet(res.data, "rows.receiptGroup") || [];
        const receiptGroup = [];
        sourceReceiptGroup.forEach((item) => {
          receiptGroup.push(...item);
        });
        receiptGroup.forEach((item) => {
          item.code = data.code;
          item.msg = data.msg;
          item.canCreateExpense = data.canCreateExpense;
          item.isOk = data.isOk;
          item.resultCode = data.resultCode;
          item.receiptLabels = errorList;
        });
        onCreate ? onCreate(receiptGroup[0], showOCRFlag, receiptGroup) : this.props.close(true);
      })
      .catch((error) => {
        errorMessage(error.response);
      })
      .finally(() => {
        this.setState({ checking: false });
      });
  };

  //保存发票For费用
  saveReceipt = (receipt) => {
    const { invoiceOID, invoiceBagId, expenseReportId, fromVICP } = this.props;
    if (!receipt.invoiceOID && invoiceOID) {
      receipt.invoiceOID = invoiceOID;
    }
    return new Promise((resolve, reject) => {
      let type = null;
      if (invoiceBagId) type = "bag";
      if (expenseReportId) type = receipt.invoiceOID ? "" : "expense_report";
      if (fromVICP) type = "VICP";
      expenseService
        .financialAuditInvoice(receipt, type, invoiceBagId || expenseReportId)
        .then((res) => {
          if (res.data.code === "0000") {
            message.success(messages("common.save.success", { arg1: "" }) /*{arg1} 保存成功*/);
            return resolve(res.data.rows);
          }
          const errorList = res.data.rows.errorList;
          const warningInfo = [];
          errorList &&
            errorList.length > 0 &&
            errorList.map((item) => {
              warningInfo.push(`${item.title}${item.title ? ":" : ""}${item.message}`);
            });

          message.error(warningInfo.join("/"));
          return reject(false);
        })
        .catch((e) => {
          errorMessage(e.response);
          return reject(false);
        });
    });
  };

  formatIdCardNo = (idCardNo) => {
    const idCardNoList = idCardNo.split("");
    const replaceList = [];
    idCardNoList.splice(10, 4).map(() => replaceList.push("*"));
    replaceList.length && idCardNoList.splice(10, 0, replaceList.join(""));
    return idCardNoList.join("");
  };

  handleUpdate = ({ type, diffs }) => {
    this.handleCancel();
    if (type === "none") {
      return;
    }
    let rInvoice = {},
      itemKey = type === "current" ? "newValue" : "oldValue",
      rMoreInfo = {};
    diffs.forEach((item) => {
      item.moreInfo ? (rMoreInfo[item.key] = item[itemKey]) : (rInvoice[item.key] = item[itemKey]);
    });
    let { errorList } = this.receiptData;
    let { moreInfo } = this.receiptData.invoiceInfo;
    moreInfo = JSON.parse(moreInfo || "{}");
    moreInfo = Object.assign({}, moreInfo, rMoreInfo);
    this.receiptData.invoiceInfo.moreInfo = JSON.stringify(moreInfo);
    this.receiptData.invoiceInfo = Object.assign({}, this.receiptData.invoiceInfo, rInvoice);
    this.receiptData.errorList = [];
    errorList.splice(
      errorList.findIndex((item) => item.code === "13794@CONFIRMATION_NEEDED"),
      1
    );
    this.receiptData.isOk = "Y";
    message.success(messages("expense-1.key812") /*更新成功*/);
    this.handleFinally(this.receiptData, this.receiptData.invoiceInfo);
  };

  handleCancel = () => {
    CommonModal.close(this.compareModal);
    this.compareModal = null;
  };

  compare = (sources) => {
    const { diffs, modifiable } = sources;
    this.compareModal = CommonModal.open(
      {
        title: messages("expense-1.key813") /*提示信息*/,
        className: "receipt-compare",
        width: "800px",
        closable: true,
        onCancel: this.handleCancel,
        footer: [
          <div className="receipt-compare-footer">
            <Button key="origin" onClick={() => this.handleUpdate({ type: modifiable ? "current" : "none", diffs })}>
              {
                modifiable
                  ? messages("expense-1.key814") /*按当前发票更新*/
                  : messages("expense-1.key815") /*退出，稍后修改原发票*/
              }
            </Button>
            {!modifiable && (
              <Popover
                content={
                  <div>
                    <h4> {messages("expense-1.key816") /*不可用当前发票覆盖原发票的值*/}</h4>
                    <p>
                      {
                        messages(
                          "expense-1.key817"
                        ) /*如果原发票归属人是他人，您可以联系对应人员商议修改原发票错误字段*/
                      }
                    </p>
                    <p>
                      {
                        messages(
                          "expense-1.key818"
                        ) /*如果原发票归属人是您自己，您可以撤回原发票所关联的报销单，才能修改原发票错误字段。*/
                      }
                    </p>
                  </div>
                }
              >
                <Icon type="question-circle-o" className="receipt-compare-ml" />
              </Popover>
            )}
          </div>,
          <Button
            key="current"
            className="receipt-compare-ml"
            onClick={() => this.handleUpdate({ type: "old", diffs })}
            type={"primary"}
          >
            {messages("expense-1.key819") /*按原发票更新*/}
          </Button>,
        ],
        params: {
          diffs,
          invoiceInfo: this.receiptData.invoiceInfo,
        },
        element: ReceiptCompare,
      },
      this,
      this.compareModal
    );
  };

  handleCompare = async (data) => {
    this.receiptData = data;
    try {
      const ret = await expenseService.getCompareRet({
        ReceiptViewDTO: data.invoiceInfo,
        isFinance: this.props.createType === 2,
      });
      this.compare(ret.data);
    } catch (e) {
      if (this.safeGet(e, "response.data.errorCode") === "13794@INVOICE_FINANCE_AUDIT_PASSED_UNEDITABLE")
        Modal.error({
          title: this.safeGet(e, "response.data.message"),
        });
      else {
        errorMessage(e.response)
      };
    }
  };
  //提交
  handleSubmit = (e) => {
    e && e.preventDefault();
    const { isAuditCheck } = this.state;
    let invoiceInfo = deepFullCopy(this.state.invoiceInfo);
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { invoiceOID, receipt } = this.props;
        const { imageIsUploading, moreInfo } = this.state;
        if (imageIsUploading) {
          message.warning(messages("expense-1.key156") /*图片上传中，请稍后*/);
          return;
        }
        //feature8810：OCR识别的区块链发票不校验校验码格式和位数（校验代码已删除）
        //手录发票时：发票类型编码=10且校验码字符串长度为5，则认为是区块链发票，不可保存
        if (!receipt.blockchain && values.invoiceTypeNo === "10" && values.checkCode && values.checkCode.length === 5) {
          Modal.info({
            title: messages(
              "expense-1.key157"
            ) /*增值税电子普通发票需输入校验码后六位数字。若票面仅有5位校验码，则为区块链发票，需要采用其他方式录入发票。*/,
          });
          return;
        }
        if (
          !receipt.blockchain &&
          values.checkCode &&
          (!/^[0-9]+$/.test(values.checkCode) || values.checkCode.length !== 6)
        ) {
          message.warning(messages("expense-1.key158") /*校验码仅支持6位数字*/);
          return;
        }
        //价税合计金额大于8位数，不可保存。
        if (values.priceTaxAmount > 1000000000) {
          message.warning(
            messages("expense-1.key159", {
              arg1: messages("expense-1.key317") /*10亿*/,
            }) /*最大值不能超过{arg1}*/
          );
          return;
        }
        invoiceInfo.cardsignType = receipt ? receipt.cardsignType || "HAND" : "HAND";
        receipt.pdfUrl && (invoiceInfo.pdfUrl = receipt.pdfUrl);
        receipt.slicingAttachment && (invoiceInfo.slicingAttachment = receipt.slicingAttachment);
        invoiceInfo.invoiceOID = invoiceOID;
        invoiceInfo.billingNo = values.invoiceNumber;
        if (receipt && receipt.id) {
          invoiceInfo.id = receipt.id;
        }
        invoiceInfo.billingCode = values.invoiceCode ? values.invoiceCode.toUpperCase() : values.invoiceCode;
        invoiceInfo.checkCode = values.checkCode;
        Object.assign(invoiceInfo, values);
        invoiceInfo.idCardNo && (invoiceInfo.idCardNo = this.formatIdCardNo(invoiceInfo.idCardNo));
        invoiceInfo.billingTime = values.invoiceDate
          ? (new Date(values.invoiceDate).getTime() / 1000).toFixed(0)
          : null;
        invoiceInfo.receiptTypeNo = invoiceInfo.invoiceTypeNo;
        if (invoiceInfo.nonVATinclusiveAmount) {
          invoiceInfo.feeWithoutTax = mulCalculate(invoiceInfo.nonVATinclusiveAmount, 100);
        } else {
          invoiceInfo.feeWithoutTax = invoiceInfo.nonVATinclusiveAmount;
        }
        if (invoiceInfo.taxAmount) {
          invoiceInfo.tax = mulCalculate(invoiceInfo.taxAmount, 100);
        } else {
          invoiceInfo.tax = invoiceInfo.taxAmount;
        }
        if (values.nonDeductibleAmount || values.nonDeductibleAmount === 0) {
          invoiceInfo.nonDeductibleAmount = mulCalculate(invoiceInfo.nonDeductibleAmount, 100);
        } else {
          invoiceInfo.nonDeductibleAmount = undefined;
        }
        if (this.checkInvoiceRender("priceTaxAmount") || this.state.additionalRecordingPriceAmountConfig) {
          if (invoiceInfo.priceTaxAmount) {
            invoiceInfo.fee = mulCalculate(invoiceInfo.priceTaxAmount, 100);
          } else {
            invoiceInfo.fee = invoiceInfo.priceTaxAmount;
          }
        }
        if (!isAuditCheck) {
          const attachment = invoiceInfo.slicingAttachmentOID;
          if (typeof attachment === "object") {
            if (attachment && attachment[0] && attachment[0].attachmentOID) {
              if (["PDF", "OFD"].includes(attachment[0].fileType)) {
                invoiceInfo.attachmentOID = attachment[0].attachmentOID;
                delete invoiceInfo.slicingAttachmentOID;
              } else {
                invoiceInfo.slicingAttachmentOID = attachment[0].attachmentOID;
              }
            } else {
              invoiceInfo.slicingAttachment = null;
              invoiceInfo.slicingAttachmentOID = null;
            }
          }
          if (!this.checkInvoiceRender("image") && invoiceInfo.cardsignType !== "OCR") {
            invoiceInfo.slicingAttachment = null;
            invoiceInfo.slicingAttachmentOID = null;
          }
        }
        invoiceInfo.receiptOwner = invoiceInfo.owner;
        invoiceInfo.moreInfo = JSON.stringify(moreInfo);
        invoiceInfo.moreInfoLabel = this.props.receipt.moreInfoLabel;
        invoiceInfo.showUserInfo = values.showUserInfo || "";
        invoiceInfo.internalStaff = values.internalStaff || "";
        invoiceInfo.agentTag = values.agentTag || "";
        invoiceInfo.domesticPassengers = values.domesticPassengers || "";
        if (values.invoiceGoods && values.invoiceGoods[0] && this.props.profile["invoice.goods.editable.tmp"]) {
          let goods = values.invoiceGoods;
          const { nonVATinclusiveAmount, taxAmount, priceTaxAmount, taxRate } = this.onInvoiceGoodsChange(goods, true);
          invoiceInfo.tax = mulCalculate(taxAmount, 100);
          invoiceInfo.feeWithoutTax = mulCalculate(nonVATinclusiveAmount, 100);
          invoiceInfo.fee = mulCalculate(priceTaxAmount, 100);
          invoiceInfo.taxRate = taxRate;
          invoiceInfo.invoiceGoods = deepFullCopy(values.invoiceGoods).map((item) => {
            item.amount = currencyPrecisionCal(values.vatInvoiceCurrencyCode, item.amount * 100);
            item.taxRate && (item.taxRate *= 100);
            item.taxRateString = item.taxRate;
            item.taxPrice = currencyPrecisionCal(values.vatInvoiceCurrencyCode, item.taxPrice * 100);
            return item;
          });
        }
        !isAuditCheck && this.testInvoice(invoiceInfo);
      } else {
        invoiceInfo = null;
      }
    });
    if (isAuditCheck) {
      return invoiceInfo;
    }
  };

  //清空补录相关信息
  clearRecordFormItem = () => {
    this.setState({
      recordTaxRateConfig: false,
      recordTaxAmountConfig: false,
      recordNonVATinclusiveAmountConfig: false,
      additionalRecordingPriceAmountConfig: false,
    });
  };

  //获取数据源
  getCurrentReceiptData = (receipt) => {
    const { currencyList } = this.props;
    let target = {};
    const hasValidValue = (field) => receipt[field] || receipt[field] === 0;
    const getShowAmount = (field) => (hasValidValue(field) ? receipt[field] / 100 : undefined);
    if (receipt) {
      //若未识别到币种或币种未启用，则置空
      let vatInvoiceCurrencyCode;
      if (currencyList && currencyList.some((item) => item.currency === receipt.vatInvoiceCurrencyCode)) {
        vatInvoiceCurrencyCode = receipt.vatInvoiceCurrencyCode || undefined;
      }
      console.log('hasValidValue("taxRate")', hasValidValue("taxRate"), receipt)
      target = {
        invoiceTypeNo: receipt.invoiceTypeNo || undefined,
        invoiceDate: receipt.billingTime ? moment(new Date(receipt.billingTime * 1000)) : undefined,
        invoiceCode: receipt.billingCode,
        invoiceNumber: receipt.billingNo,
        vatInvoiceCurrencyCode,
        taxRate: hasValidValue("taxRate") ? receipt.taxRate || Number(receipt.invoiceGoods[0].taxRate) / 100 : receipt.invoiceGoods[0].taxRate ? Number(receipt.invoiceGoods[0].taxRate) / 100 : undefined,
        taxAmount: getShowAmount("tax"),
        priceTaxAmount: getShowAmount("tmpFee") || getShowAmount("fee"),
        nonVATinclusiveAmount: getShowAmount("feeWithoutTax"),
        nonDeductibleAmount: getShowAmount("nonDeductibleAmount"),
        checkCode: receipt.checkCode ? receipt.checkCode.slice(-6) : receipt.checkCode,
        owner: receipt.receiptOwner,
        idCardNo: receipt.idCardNo,
        agentTag: receipt.agentTag || undefined,
        showUserInfo: receipt.showUserInfo || undefined,
        internalStaff: receipt.internalStaff || undefined,
        domesticPassengers: receipt.domesticPassengers || undefined,
      };
      if (receipt.invoiceTypeNo === "150" && getShowAmount("tmpFee")) {
        target.totalAmount = getShowAmount("tmpFee");
      }
    }
    return target;
  };

  getDefaultTaxRate = (invoiceTypeNo) => {
    const { invoiceTypes, taxRates } = this.state;
    const currentInvoiceType = invoiceTypes.find((type) => type.value === invoiceTypeNo) || {};
    const defaultTaxRate = taxRates.find((rate) => rate.taxRateKey === currentInvoiceType.remark) || {};
    return defaultTaxRate.taxRateValue;
  };
  //初始化值发票控件值
  initReceiptValue = async (receipt) => {
    let currentReceipt;
    const { receiptTipImages } = this.state;
    //编辑
    if (receipt && JSON.stringify(receipt) !== "{}") {
      currentReceipt = this.getCurrentReceiptData(receipt);
      if (!receipt.invoiceTypeNo) {
        this.setFieldsValues(currentReceipt);
        return;
      }
      // 为机票和小票时 需要显示不可抵扣及总金额
      // 小票默认值为0 机票为50
      const defaultValueMap = {
        170: 0,
        150: 50,
      };
      if (["170", "150"].includes(receipt.invoiceTypeNo)) {
        currentReceipt.nonDeductibleAmount =
          // 新建的机票和小票才会有默认的不可抵扣
          (!currentReceipt.invoiceTypeNo || receipt.isHandNew) && currentReceipt.nonDeductibleAmount === undefined
            ? defaultValueMap[receipt.invoiceTypeNo]
            : currentReceipt.nonDeductibleAmount;
        //【总金额】= 【价税合计】+【不可抵扣】
        if (currentReceipt.totalAmount) {
          currentReceipt.priceTaxAmount = currentReceipt.totalAmount - (currentReceipt.nonDeductibleAmount || 0);
        } else {
          currentReceipt.totalAmount = (currentReceipt.priceTaxAmount || 0) + (currentReceipt.nonDeductibleAmount || 0);
        }
      }
      const defaultTaxRate = this.getDefaultTaxRate(receipt.invoiceTypeNo);
      !currentReceipt.taxRate &&
        currentReceipt.taxRate !== 0 &&
        defaultTaxRate &&
        defaultTaxRate !== 0 &&
        (currentReceipt.taxRate = defaultTaxRate);
      const res = await this.receiptTypeInit(currentReceipt.invoiceTypeNo);
      const [receiptConfigList, image] = res;
      image && (receiptTipImages[currentReceipt.invoiceTypeNo] = image);
      this.setState(
        {
          receiptConfigList,
          receiptTipImages,
        },
        () => {
          currentReceipt = this.editExitFormItem(currentReceipt);
          this.setFieldsValues(currentReceipt);
        }
      );
    }
    this.checkSuccessByCode(receipt.resultCode);
  };

  handleReRenderFormItemForReceiptNo = () => {
    const { getFieldValue } = this.props.form;
    let currentReceipt;
    const invoiceTypeNoValue = getFieldValue("invoiceTypeNo");
    currentReceipt = this.props.receipt;
    currentReceipt = this.getCurrentReceiptData(currentReceipt);
    currentReceipt.totalAmount = currentReceipt.priceTaxAmount;
    currentReceipt = this.editExitFormItem(currentReceipt, true);
    // 为机票和小票时 需要显示不可抵扣及总金额
    // 小票默认值为0 机票为50
    const defaultValueMap = {
      170: 0,
      150: 50,
    };
    if (["170", "150"].includes(invoiceTypeNoValue)) {
      //【总金额】= 【价税合计】+【不可抵扣】
      currentReceipt.nonDeductibleAmount =
        currentReceipt.nonDeductibleAmount === undefined
          ? defaultValueMap[invoiceTypeNoValue]
          : currentReceipt.nonDeductibleAmount;
      if (currentReceipt.totalAmount || currentReceipt.totalAmount === 0) {
        currentReceipt.priceTaxAmount = currentReceipt.totalAmount - currentReceipt.nonDeductibleAmount;
      }
    }
    this.setFieldsValues(currentReceipt);
  };

  receiptTypeInit = async (receiptNo) => {
    const { receiptTipImages } = this.state;
    return await Promise.all([
      this.queryReceiptShow(receiptNo),
      !receiptTipImages[receiptNo] && this.getTipImg(receiptNo),
    ]);
  };

  //发票类型改变
  handleReceiptNoChange = async (receiptNo) => {
    const { receiptTipImages } = this.state;
    // 人工核票页面更换发票类型时，需要联动，另一侧也要改
    this.props.setReceiptNo && this.props.setReceiptNo(receiptNo);
    const res = await this.receiptTypeInit(receiptNo);
    const [receiptConfigList, image] = res;
    this.setState({ receiptConfigList }, this.handleReRenderFormItemForReceiptNo); //初始化默认值
    image && (receiptTipImages[receiptNo] = image);
    this.setState({ receiptTipImages });
    if (!this.checkInvoiceRender("taxRate")) {
      return;
    }
    const defaultTaxRate = this.getDefaultTaxRate(receiptNo);
    const currentTaxRate = this.getFormItemValue("taxRates");
    if (currentTaxRate !== defaultTaxRate && (defaultTaxRate || defaultTaxRate === 0)) {
      this.setFieldsValues({ taxRate: defaultTaxRate });
      this.handleChangeTaxRate(defaultTaxRate);
    }
  };

  //获取表单值
  getFormItemValue = (formItemId) => {
    const { getFieldsValue, getFieldValue } = this.props.form;
    return getFieldsValue().hasOwnProperty(formItemId) ? getFieldValue(formItemId) : "";
  };

  //获取发票对应公司
  getReceiptCompany = () => {
    let company;
    const { documentaryCompany } = this.props;
    if (documentaryCompany && documentaryCompany.id) {
      company = documentaryCompany;
    } else {
      company = this.props.company;
    }
    return company;
  };
  //查询控件显示
  queryReceiptShow = (receiptNo) => {
    return new Promise((resolve, reject) => {
      const { onLoadingFinished, receipt } = this.props;
      let { companyOpenInvoice } = this.state;
      let company = this.getReceiptCompany();
      this.setState({ loading: true });
      expenseService
        .getReceiptDisplay(companyOpenInvoice, receiptNo, company.tenantId, company.setOfBooksId, company.id)
        .then((res) => {
          if (res.data && res.data.rows && res.data.rows.length > 0 && res.data.rows[0].hitValue) {
            this.setState({ loading: false });
            let receiptConfigList = JSON.parse(res.data.rows[0].hitValue);
            receipt && onLoadingFinished && receipt.id && onLoadingFinished(receipt.id);
            resolve(receiptConfigList);
          }
        })
        .catch((e) => {
          console.error(e)
          this.setState({ loading: false });
          errorMessage(e.response);
          this.clearRecordFormItem();
          reject([]);
        });
    });
  };

  //修改存在的FormItem项,isCoverFormItem是否覆盖form项
  //切换发票类型后，若“税率/税额/不含税金额/价税合计”配置不显示，则清空值
  editExitFormItem(inits, invoiceTypeChanged) {
    const { getFieldsValue, getFieldValue } = this.props.form;
    const dealAmountList = ["taxRate", "taxAmount", "nonVATinclusiveAmount", "priceTaxAmount"];
    const { invoiceInfo } = this.state;
    const exitVar = {};
    if (getFieldsValue() && inits) {
      Object.keys(inits).map((item) => {
        if (!getFieldValue(item) && inits[item] !== undefined && inits[item] !== null) {
          exitVar[item] = inits[item];
        }
        if (invoiceTypeChanged && dealAmountList.includes(item) && this.checkInvoiceRender(item, 4) === "10") {
          exitVar[item] = undefined;
          invoiceInfo[receiptFieldItemMap[item] || item] = undefined;
          item === "taxAmount" && (invoiceInfo.taxString = undefined);
        }
      });
    }
    this.setState({ invoiceInfo });
    return exitVar;
  }

  /**
   * 税率改变时修改税额、不含税金额
   * @param value
   */
  handleChangeTaxRate = (value) => {
    if (!value && value !== 0) return;
    const { getFieldsValue, getFieldValue } = this.props.form;
    const amount = getFieldValue("priceTaxAmount");
    let nonVATinclusiveAmount;
    if (getFieldsValue().hasOwnProperty("nonVATinclusiveAmount")) {
      nonVATinclusiveAmount = getFieldValue("nonVATinclusiveAmount");
    }
    const vatInvoiceCurrencyCodeValue = this.getFormItemValue("vatInvoiceCurrencyCode");
    const currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    if (Math.abs(Number(amount)) >= 0) {
      const nonVATinclusiveAmount = Number((amount / (1 + value)).toFixed(currencyPrecision));
      const taxAmount = Number((amount - nonVATinclusiveAmount).toFixed(currencyPrecision));
      this.setFieldsValues({ nonVATinclusiveAmount: nonVATinclusiveAmount, taxAmount: taxAmount });
    } else if (nonVATinclusiveAmount) {
      const priceTaxAmount = Number(+nonVATinclusiveAmount * (1 + value)).toFixed(currencyPrecision);
      const taxAmount = Number((priceTaxAmount - nonVATinclusiveAmount).toFixed(currencyPrecision));
      this.setFieldsValues({
        priceTaxAmount: priceTaxAmount,
        taxAmount: taxAmount,
        nonVATinclusiveAmount: this.getCurrencyPrecisionValue(nonVATinclusiveAmount),
      });
    }
    this.handleInvoiceGoods({ code: "taxRate", value });
  };
  /**
   * 税额改变时修改不含税金额
   * @param value
   */
  handleChangeTaxAmount = (value) => {
    const { getFieldsValue, getFieldValue } = this.props.form;
    const amount = getFieldValue("priceTaxAmount");
    //避免金额合计控件不显示，强行计算
    if (!getFieldsValue().hasOwnProperty("nonVATinclusiveAmount")) {
      return;
    }
    const nonVATinclusiveAmount = amount - value;
    !isNaN(nonVATinclusiveAmount) &&
      this.setFieldsValues({
        nonVATinclusiveAmount: this.getCurrencyPrecisionValue(nonVATinclusiveAmount),
      });
    this.handleInvoiceGoods({ code: "taxAmount", value });
  };
  //获取币种金额值
  getCurrencyPrecisionValue = (value) => {
    const vatInvoiceCurrencyCodeValue = this.getFormItemValue("vatInvoiceCurrencyCode");
    const currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    return Number(Number(value).toFixed(currencyPrecision));
  };

  /**
   * 价税合计改变修改税额、不含税金额
   */
  handleChangePriceTaxAmount = (amount) => {
    const { getFieldValue } = this.props.form;
    const taxRate = getFieldValue("taxRate");
    const vatInvoiceCurrencyCodeValue = this.getFormItemValue("vatInvoiceCurrencyCode");
    const currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    if (Number(taxRate) >= 0) {
      amount = parseFloat(amount);
      if (isNaN(amount)) {
        amount = 0;
      }
      const nonVATinclusiveAmount = Number((amount / (1 + taxRate)).toFixed(currencyPrecision));
      const taxAmount = Number((amount - nonVATinclusiveAmount).toFixed(currencyPrecision));
      this.setFieldsValues({ nonVATinclusiveAmount: nonVATinclusiveAmount, taxAmount: taxAmount });
    }
    this.handleInvoiceGoods({ code: "priceTaxAmount", value: amount });
  };

  //币种选择改变
  selectVatInvoiceCurrencyCodeChange = (value) => {
    const currcyAccuracyRelate = ["priceTaxAmount", "taxAmount", "nonVATinclusiveAmount"];
    const { getFieldValue } = this.props.form;
    currcyAccuracyRelate.map((item) => {
      this.setFieldsValues({ [item]: Number(currencyPrecisionCal(value, getFieldValue(item))) });
    });
  };

  handleValidator = (rule, value, callback) => {
    // 处理报错
    const { getFieldValue } = this.props.form;
    const priceTaxAmountValue = getFieldValue("priceTaxAmount");
    const { recordTaxAmountConfig, recordNonVATinclusiveAmountConfig } = this.state;
    const arrSpeech = {};
    let middleConfig;
    if (rule.field === "taxAmount") {
      arrSpeech.speechOne = messages("expense-1.key160") /*税额合计的绝对值不能大于价税合计的绝对值*/;
      arrSpeech.speechTwo = messages("expense-1.key161") /*税额合计与价税合计的符号必须一致！*/;
      middleConfig = recordTaxAmountConfig;
    }
    if (rule.field === "nonVATinclusiveAmount") {
      arrSpeech.speechOne = messages("expense-1.key162") /*金额合计(不含税)的绝对值不能大于价税合计的绝对值*/;
      arrSpeech.speechTwo = messages("expense-1.key163") /*金额合计(不含税)与价税合计的符号必须一致！*/;
      middleConfig = recordNonVATinclusiveAmountConfig;
    }
    if (Math.abs(value) > Math.abs(priceTaxAmountValue)) {
      // 金额合计不能大于价税合计
      callback(arrSpeech.speechOne);
    } else if ((value > 0 && priceTaxAmountValue < 0) || (priceTaxAmountValue > 0 && value < 0)) {
      callback(arrSpeech.speechTwo);
    } else if ((middleConfig || this.checkInvoiceRender(rule.field, 2)) && (value === undefined || value === null)) {
      callback(messages("common.please.input") /*请输入*/);
    } else {
      callback();
    }
  };

  setFieldsValues = (values) => {
    const valuesFilter = {};
    Object.keys(values).forEach(
      (key) => this.props.form.getFieldsValue().hasOwnProperty(key) && (valuesFilter[key] = values[key])
    );
    this.props.form.setFieldsValue({ ...valuesFilter });
  };
  //联动关系：【价税合计】=【总金额】-【不可抵扣】
  //价税合计变化，有税率时，重算税额和不含税金额：【价税合计】=【税额】+【不含税金额】
  handleAmountLinkage = (type, value = 0) => {
    const priceTaxAmount = Number(this.getFormItemValue("priceTaxAmount") || 0);
    const totalAmount = this.getFormItemValue("totalAmount");
    const nonDeductibleAmount = Number(this.getFormItemValue("nonDeductibleAmount") || 0);
    const currencyCode = this.getFormItemValue("vatInvoiceCurrencyCode");
    const precision = queryCurrencyPrecision(currencyCode);
    value = Number(isNaN(value) ? 0 : value);
    //若总金额为空，需要计算总金额
    if (!totalAmount && totalAmount !== 0 && type !== "totalAmount") {
      if (type === "priceTaxAmount") {
        //价税合计
        this.setFieldsValues({
          totalAmount: (value + nonDeductibleAmount).toFixed(precision),
        });
        this.handleChangePriceTaxAmount(value);
      }
      if (type === "nonDeductibleAmount") {
        //不可抵扣
        this.setFieldsValues({
          totalAmount: (value + priceTaxAmount).toFixed(precision),
        });
      }
    } else {
      if (type === "priceTaxAmount") {
        //价税合计
        this.setFieldsValues({
          nonDeductibleAmount: (totalAmount - value).toFixed(precision),
        });
        this.handleChangePriceTaxAmount(value);
      }
      if (type === "totalAmount") {
        //总金额
        this.setFieldsValues({
          priceTaxAmount: (value - nonDeductibleAmount).toFixed(precision),
        });
        this.handleChangePriceTaxAmount(value - nonDeductibleAmount);
      }
      if (type === "nonDeductibleAmount") {
        //不可抵扣
        this.setFieldsValues({
          priceTaxAmount: (totalAmount - value).toFixed(precision),
        });
        this.handleChangePriceTaxAmount(totalAmount - value);
      }
    }
  };

  //没有发票类型时是否显示formItem
  //因为OCR查验发票可能没有识别出发票类型但却有其它的值
  showItemWithoutCode = (type) => {
    const {
      receipt,
      form: { getFieldValue },
    } = this.props;
    const { isAuditCheck } = this.state;
    return !isAuditCheck && !getFieldValue("invoiceTypeNo") && !!(receipt[type] || receipt[type] === 0);
  };

  //修改更多信息
  handleMoreInfoChange = (isMoreInfo, value) => {
    if (isMoreInfo) {
      this.setState({ moreInfo: value });
    } else {
      const { invoiceInfo } = this.state;
      Object.keys(value).map((key) => {
        invoiceInfo[key] = value[key];
      });
      this.setState({ invoiceInfo });
    }
  };

  /**
   * 判断是否需要展示【更多信息】
   * 需展示场景
   *    1: moreInfo字段有值且不为"{}"
   *    2: 【销售方名称、销售方纳税人识别号、购买方名称、购买方纳税人识别号】字段任意一个有值
   */
  isMoreInfoShow = () => {
    const { receipt } = this.props;
    const needShowKey = ["payee", "payeeNo", "title", "draweeNo"];
    let isShow = false;
    if (receipt.moreInfo && receipt.moreInfo !== "{}") {
      isShow = true;
    }
    needShowKey.map((key) => {
      if (receipt[key]) {
        isShow = true;
      }
    });
    return isShow;
  };

  //发票录入修改
  renderInvoiceArea = () => {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { currencyList, invoiceUserFp, onBack, currency, language, receipt, renderCoverIcon } = this.props;
    const {
      taxRates,
      invoiceTypes,
      recordTaxRateConfig,
      recordTaxAmountConfig,
      recordNonVATinclusiveAmountConfig,
      additionalRecordingPriceAmountConfig,
      checking,
      invoiceOptionsFetching,
      receiptTipImages,
      isAuditCheck,
      attachmentEditable,
    } = this.state;
    const invoiceDate = "invoiceDate"; //开票日期
    const invoiceCode = "invoiceCode"; // 发票代码
    const invoiceNumber = "invoiceNumber"; // 发票号码
    const vatInvoiceCurrencyCode = "vatInvoiceCurrencyCode"; // 币种
    const nonVATinclusiveAmount = "nonVATinclusiveAmount"; // 总金额
    const taxRate = "taxRate"; // 税率
    const taxAmount = "taxAmount"; // 税额合计
    const priceTaxAmount = "priceTaxAmount"; // 价税合计
    const checkCode = "checkCode"; // 校验码
    const owner = "owner"; // 归属人
    const invoiceTypeNoValue = getFieldValue("invoiceTypeNo");
    const vatInvoiceCurrencyCodeValue = this.getFormItemValue(vatInvoiceCurrencyCode);
    const currencyPrecision = queryCurrencyPrecision(vatInvoiceCurrencyCodeValue);
    const formItemLayout = isAuditCheck
      ? {
          labelCol: { span: 9 },
          wrapperCol: { span: 15 },
        }
      : {
          labelCol: { span: 5 },
          wrapperCol: { span: 10 },
        };
    return (
      <Form
        className={`create-invoice ${isAuditCheck ? "audit-check-invoice" : "new-form"}`}
        onSubmit={this.handleSubmit}
      >
        {/*OCR发票永远不可删除与修改*/}
        {!isAuditCheck &&
          !attachmentEditable &&
          receipt.cardsignType === "OCR" &&
          receipt.slicingAttachment &&
          receipt.slicingAttachment.fileURL && (
            <FormItem label={messages("expense-1.key164") /*发票附件*/} {...formItemLayout}>
              <Condition>
                <If value={window.ISIE9}>
                  <IeFileUpload defaultFileList={[receipt.slicingAttachment]} disabled />
                </If>
                <Else>
                  <FileUpload
                    defaultFileList={[receipt.slicingAttachment]}
                    attachmentType="INVOICE_IMAGES"
                    showFileName={false}
                    disabled
                  />
                </Else>
              </Condition>
            </FormItem>
          )}
        <If value={(receipt.cardsignType !== "OCR" || attachmentEditable) && this.checkInvoiceRender("image")}>
          {isAuditCheck ? (
            <FormItem
              label={<span className="ant-form-item-required">{messages("expense-1.key164") /*发票附件*/}</span>}
              {...formItemLayout}
            >
              {messages("expense-1.key165") /*到发票列表补填*/}
            </FormItem>
          ) : (
            <FormItem
              label={messages("expense-1.key164") /*发票附件*/}
              {...formItemLayout}
              extra={invoiceAttachmentInfo(this.checkInvoiceRender("image", 4), "extra")}
            >
              {window.ISIE9
                ? getFieldDecorator("slicingAttachmentOID", {
                    rules: [
                      {
                        required: this.checkInvoiceRender("image", 2),
                        message: `${messages("common.select") /*请选择*/}`,
                      },
                    ],
                    initialValue: receipt.slicingAttachmentOID,
                  })(
                    <IeImgUpload
                      defaultFileList={receipt.slicingAttachment ? [receipt.slicingAttachment] : []}
                      attachmentType="INVOICE_IMAGES"
                      showFileName={false}
                      disabled={this.checkInvoiceRender("image", 3)}
                      maxNum={1}
                    />
                  )
                : getFieldDecorator("slicingAttachmentOID", {
                    rules: [
                      {
                        required: this.checkInvoiceRender("image", 2),
                        message: `${messages("common.select") /*请选择*/}`,
                      },
                    ],
                    initialValue: receipt.slicingAttachmentOID,
                  })(
                    <ImageUpload
                      defaultFileList={
                        receipt.slicingAttachment && !attachmentEditable ? [receipt.slicingAttachment] : []
                      }
                      attachmentType="INVOICE_IMAGES"
                      fileType={invoiceAttachmentInfo(this.checkInvoiceRender("image", 4), "fileType")}
                      accept={invoiceAttachmentInfo(this.checkInvoiceRender("image", 4), "accept")}
                      showFileName={false}
                      disabled={this.checkInvoiceRender("image", 3)}
                      maxNum={1}
                      isUploading={(value) => this.setState({ imageIsUploading: value })}
                    />
                  )}
            </FormItem>
          )}
        </If>
        {(!isAuditCheck || this.auditInvoiceItemShow("type")) && (
          <div style={{ position: "relative" }}>
            <FormItem label={messages("common.invoice.type") /*发票类型*/} {...formItemLayout}>
              {getFieldDecorator("invoiceTypeNo", {
                rules: [
                  {
                    required: true,
                    message: messages("common.select") /*请选择*/,
                  },
                ],
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  onChange={this.handleReceiptNoChange}
                  dropdownClassName="create-invoice-select-invoice-type"
                  notFoundContent={
                    invoiceOptionsFetching ? <Spin size="small" /> : messages("common.unmatched") /*无匹配结果*/
                  }
                  placeholder={messages("common.select") /*请选择*/}
                  disabled={this.checkInvoiceRender("invoiceTypeNo", 3)}
                >
                  {invoiceTypes.map((item) => (
                    <Option key={item.value} disabled={!item.isEnable} style={{ whiteSpace: "normal" }}>
                      {item.messageKey}
                    </Option>
                  ))}
                </Select>
              )}
              {renderCoverIcon && renderCoverIcon("invoiceTypeNo")}
            </FormItem>
            <If value={!isAuditCheck && invoiceTypeNoValue && receiptTipImages[invoiceTypeNoValue]}>
              <Popover
                placement="bottomRight"
                overlayClassName="invoice-input-notes-popover"
                overlayStyle={{ maxWidth: "none", paddingBottom: 10 }}
                content={<img style={{ width: "35vw" }} src={receiptTipImages[invoiceTypeNoValue]} />}
                getPopupContainer={() => document.getElementsByClassName("invoice-input-notes-container")[0]}
              >
                <a className="invoice-info">{messages("expense-1.key166") /*填写说明*/}</a>
              </Popover>
            </If>
          </div>
        )}
        <div>
          {(this.checkInvoiceRender(invoiceCode) || this.showItemWithoutCode("billingCode")) && (
            <FormItem label={messages("expense-1.key78") /*发票代码*/} {...formItemLayout}>
              {getFieldDecorator(invoiceCode, {
                rules: [
                  {
                    required: this.checkInvoiceRender(invoiceCode, 2),
                    message: `${messages("common.please.input") /*请输入*/}`,
                  },
                  {
                    max: 50,
                    message: messages("common.max.characters.length", {
                      arg1: 50,
                    }) /*最多输入{arg1}个字符*/,
                  },
                  {
                    validator: (rule, value, callback) => {
                      if (/^[A-Za-z0-9]{0,50}$/.test(value)) {
                        callback();
                      } else {
                        callback(messages("expense-1.key167") /*请输入字母或数字*/);
                      }
                    },
                  },
                ],
              })(
                <Input
                  placeholder={messages("expense-1.key56") /*请输入temp2*/}
                  disabled={this.checkInvoiceRender(invoiceCode, 3)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("invoiceCode")}
            </FormItem>
          )}
          {(this.checkInvoiceRender(invoiceNumber) || this.showItemWithoutCode("billingNo")) && (
            <FormItem label={messages("expense-1.key79") /*发票号码*/} {...formItemLayout}>
              {getFieldDecorator(invoiceNumber, {
                rules: [
                  {
                    required: this.checkInvoiceRender(invoiceNumber, 2),
                    message: messages("common.please.input") /*请输入*/,
                  },
                  {
                    max: 50,
                    message: messages("common.max.characters.length", {
                      arg1: 50,
                    }) /*最多输入{arg1}个字符*/,
                  },
                  {
                    validator: (rule, value, callback) => {
                      if (/^[A-Za-z0-9]{0,50}$/.test(value)) {
                        callback();
                      } else {
                        callback(messages("expense-1.key167") /*请输入字母或数字*/);
                      }
                    },
                  },
                ],
              })(
                <Input
                  placeholder={messages("expense-1.key56") /*请输入temp2*/}
                  disabled={this.checkInvoiceRender(invoiceNumber, 3)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("invoiceNumber")}
            </FormItem>
          )}
          {(this.checkInvoiceRender(invoiceDate) || this.showItemWithoutCode("billingTime")) && (
            <FormItem label={messages("expense-1.key77") /*开票日期*/} {...formItemLayout}>
              {getFieldDecorator(invoiceDate, {
                rules: [
                  {
                    required: this.checkInvoiceRender(invoiceDate, 2),
                    message: messages("common.please.input") /*请输入*/,
                  },
                ],
              })(
                <DatePicker
                  placeholder={messages("common.select") /*请选择*/}
                  disabledDate={this.disabledDate}
                  disabled={this.checkInvoiceRender(invoiceDate, 3)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("invoiceDate")}
            </FormItem>
          )}
          {((!isAuditCheck && recordTaxRateConfig) ||
            this.checkInvoiceRender(taxRate) ||
            this.showItemWithoutCode("taxRate")) && (
            <FormItem label={messages("expense-1.key69") /*税率*/} {...formItemLayout}>
              {getFieldDecorator(taxRate, {
                rules: [
                  {
                    required: recordTaxRateConfig || this.checkInvoiceRender(taxRate, 2),
                    message: messages("common.select") /*请选择*/,
                  },
                ],
              })(
                <Select
                  placeholder={messages("common.select") /*请选择*/}
                  onChange={this.handleChangeTaxRate}
                  disabled={this.checkInvoiceRender("taxRate", 3)}
                >
                  {taxRates.map((tax) => {
                    return (
                      <Option value={tax.taxRateValue} key={tax.taxRateValue}>
                        {tax.taxRateKey}
                      </Option>
                    );
                  })}
                </Select>
              )}
              {renderCoverIcon && renderCoverIcon("taxRate")}
            </FormItem>
          )}
          {(this.checkInvoiceRender(vatInvoiceCurrencyCode) || this.showItemWithoutCode("vatInvoiceCurrencyCode")) && (
            <FormItem label={messages("common.currency") /*币种*/} {...formItemLayout}>
              {getFieldDecorator(vatInvoiceCurrencyCode, {
                rules: [
                  {
                    required: this.checkInvoiceRender(vatInvoiceCurrencyCode, 2),
                    message: messages("common.select") /*请选择*/,
                  },
                ],
                initialValue: currency,
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  placeholder={messages("common.select") /*请选择*/}
                  onChange={this.selectVatInvoiceCurrencyCodeChange}
                  disabled={this.checkInvoiceRender("vatInvoiceCurrencyCode", 3)}
                >
                  {currencyList.map((item) => {
                    return (
                      <Option key={item.currency}>
                        {item.currency}
                        {language.code === "zh_cn" ? ` ${item.currencyName}` : ""}
                      </Option>
                    );
                  })}
                </Select>
              )}
              {renderCoverIcon && renderCoverIcon("vatInvoiceCurrencyCode")}
            </FormItem>
          )}

          {!isAuditCheck && ["150", "170"].includes(invoiceTypeNoValue) && (
            <FormItem label={messages("common.total.amount") /*总金额*/} {...formItemLayout}>
              {getFieldDecorator("totalAmount", {
                rules: [
                  {
                    required: true,
                    message: messages("common.please.input") /*请输入*/,
                  },
                ],
              })(
                <InputNumber
                  placeholder={messages("expense-1.key168") /*行程单“合计”*/}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  onChange={(value) => this.handleAmountLinkage("totalAmount", value)}
                />
              )}
            </FormItem>
          )}

          {((!isAuditCheck && additionalRecordingPriceAmountConfig) ||
            this.checkInvoiceRender(priceTaxAmount) ||
            this.showItemWithoutCode("fee")) && (
            <FormItem label={messages("expense-1.key87") /*价税合计*/} {...formItemLayout}>
              {getFieldDecorator(priceTaxAmount, {
                rules: [
                  {
                    required: additionalRecordingPriceAmountConfig || this.checkInvoiceRender(priceTaxAmount, 2),
                    message: messages("common.please.input") /*请输入*/,
                  },
                  {
                    //fix bug 25064 金额有最大值时，不能显示超过最大值的数据
                    validator: (rule, value, callback) => {
                      const max = 1000000000;
                      if (value === "-" || Math.abs(value) <= max || value === undefined) {
                        callback();
                      } else {
                        callback(
                          messages("expense-1.key159", {
                            arg1: messages("expense-1.key317") /*10亿*/,
                          }) /*最大值不能超过{arg1}*/
                        );
                      }
                    },
                  },
                ],
              })(
                <InputNumber
                  min={-1000000000}
                  placeholder={messages("common.please.input") /*请输入*/}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  disabled={this.checkInvoiceRender(priceTaxAmount, 3)}
                  onChange={(value) => this.handleAmountLinkage("priceTaxAmount", value)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("priceTaxAmount")}
            </FormItem>
          )}

          {((!isAuditCheck && ["150", "170"].includes(invoiceTypeNoValue)) ||
            this.showItemWithoutCode("nonDeductibleAmount")) && (
            <FormItem label={messages("expense-1.key91") /*不可抵扣*/} {...formItemLayout}>
              {getFieldDecorator("nonDeductibleAmount", {
                rules: [
                  {
                    required: true,
                    message: messages("common.please.input") /*请输入*/,
                  },
                ],
              })(
                <InputNumber
                  placeholder={messages("common.please.input") /*请输入*/}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  onChange={(value) => this.handleAmountLinkage("nonDeductibleAmount", value)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("nonDeductibleAmount")}
            </FormItem>
          )}

          {((!isAuditCheck && recordTaxAmountConfig) ||
            this.checkInvoiceRender(taxAmount) ||
            this.showItemWithoutCode("tax")) && (
            <FormItem label={messages("expense-1.key90") /*税额合计*/} {...formItemLayout}>
              {getFieldDecorator(taxAmount, {
                rules: [
                  {
                    required: recordTaxAmountConfig || this.checkInvoiceRender(taxAmount, 2),
                    validator: this.handleValidator,
                  },
                ],
              })(
                <InputNumber
                  placeholder={messages("common.please.input") /*请输入*/}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  disabled={this.checkInvoiceRender(taxAmount, 3)}
                  onChange={this.handleChangeTaxAmount}
                />
              )}
              {renderCoverIcon && renderCoverIcon("taxAmount")}
            </FormItem>
          )}
          {((!isAuditCheck && recordNonVATinclusiveAmountConfig) ||
            this.checkInvoiceRender(nonVATinclusiveAmount) ||
            this.showItemWithoutCode("feeWithoutTax")) && (
            <FormItem
              label={`${messages("expense-1.key88") /*金额合计*/}（${messages("expense-1.key89") /*不含税*/}）`}
              {...formItemLayout}
            >
              {getFieldDecorator(nonVATinclusiveAmount, {
                rules: [
                  {
                    required: recordNonVATinclusiveAmountConfig || this.checkInvoiceRender(nonVATinclusiveAmount, 2),
                    validator: this.handleValidator,
                  },
                ],
              })(
                <InputNumber
                  placeholder={messages("common.please.input") /*请输入*/}
                  precision={currencyPrecision}
                  step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                  disabled={this.checkInvoiceRender(nonVATinclusiveAmount, 3)}
                  onChange={this.handleChangeNonVATinclusiveAmount}
                />
              )}
              {renderCoverIcon && renderCoverIcon("nonVATinclusiveAmount")}
            </FormItem>
          )}
          {(this.checkInvoiceRender(checkCode) || this.showItemWithoutCode("checkCode")) && (
            <FormItem label={messages("expense-1.key81") /*校验码*/} {...formItemLayout}>
              {getFieldDecorator(checkCode, {
                rules: [
                  {
                    required: this.checkInvoiceRender(checkCode, 2),
                    message: messages("common.name.is.required", {
                      arg1: messages("expense-1.key81") /*校验码*/,
                    }) /*{arg1}必填*/,
                  },
                  {
                    min: 5,
                    message: messages("expense-1.key169") /*请输入校验码后6位*/,
                  },
                  {
                    max: 6,
                    message: messages("expense-1.key169") /*请输入校验码后6位*/,
                  },
                  {
                    pattern: "^[0-9a-zA-Z]{1,}$",
                    message: messages("expense-1.key170") /*只支持数字和字母*/,
                  },
                ],
              })(
                <Input
                  placeholder={messages("expense-1.key171") /*校验码后6位*/}
                  maxLength="6"
                  disabled={this.checkInvoiceRender(checkCode, 3)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("checkCode")}
            </FormItem>
          )}
          {(this.checkInvoiceRender(owner) || this.showItemWithoutCode("receiptOwner")) && (
            <FormItem label={messages("expense-1.key82") /*归属人*/} {...formItemLayout}>
              {getFieldDecorator(owner, {
                rules: [
                  {
                    required: this.checkInvoiceRender(owner, 2),
                    message: messages("expense-1.key172") /*请输入归属人*/,
                  },
                  {
                    max: 50,
                    message: messages("common.max.characters.length", {
                      arg1: 50,
                    }) /*最多输入{arg1}个字符*/,
                  },
                ],
              })(
                <Input
                  placeholder={messages("common.please.input") /*请输入*/}
                  disabled={this.checkInvoiceRender(owner, 3)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("owner")}
            </FormItem>
          )}
          {this.checkInvoiceRender("idCardNo") && (
            <FormItem label={messages("expense-1.key83") /*身份证号*/} {...formItemLayout}>
              {getFieldDecorator("idCardNo", {
                rules: [
                  {
                    required: this.checkInvoiceRender("idCardNo", 2),
                    message: messages("common.please.input") /*请输入*/,
                  },
                  {
                    max: 20,
                    message: messages("common.max.characters.length", {
                      arg1: 20,
                    }) /*最多输入{arg1}个字符*/,
                  },
                  {
                    validator: (rule, value, callback) => {
                      if (value && !value.match("^[0-9a-zA-Z*]*$")) {
                        callback(messages("expense-1.key173") /*只允许填写字母、数字或**/);
                      }
                      callback();
                    },
                  },
                ],
              })(
                <Input
                  placeholder={messages("common.please.input") /*请输入*/}
                  disabled={this.checkInvoiceRender("idCardNo", 3)}
                />
              )}
              {renderCoverIcon && renderCoverIcon("idCardNo")}
            </FormItem>
          )}
          {this.checkInvoiceRender("personInfo") && (
            <FormItem label={messages("expense-1.key84") /*人员信息*/} {...formItemLayout}>
              {getFieldDecorator("showUserInfo", {
                rules: [
                  {
                    required: this.checkInvoiceRender("personInfo", 2),
                    message: messages("common.select") /*请选择*/,
                  },
                ],
              })(
                <Select
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  allowClear
                  optionLabelProp="title"
                  disabled={this.checkInvoiceRender("personInfo", 3)}
                  placeholder={messages("common.select") /*请选择*/}
                >
                  {showUserInfoOptions.map((item) => (
                    <Option key={item.key} title={item.title} style={{ whiteSpace: "normal" }}>
                      {item.value}
                    </Option>
                  ))}
                </Select>
              )}
              {renderCoverIcon && renderCoverIcon("showUserInfo")}
            </FormItem>
          )}
          {this.checkInvoiceRender("internal") && (
            <FormItem label={messages("expense-1.key85") /*是否内部员工发票*/} {...formItemLayout}>
              {getFieldDecorator("internalStaff", {
                rules: [
                  {
                    required: this.checkInvoiceRender("internal", 2),
                    message: messages("common.select") /*请选择*/,
                  },
                ],
              })(
                <Select
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  allowClear
                  disabled={this.checkInvoiceRender("internal", 3)}
                  placeholder={messages("common.select") /*请选择*/}
                >
                  {internalOptions.map((item) => (
                    <Option key={item.key}>{item.value}</Option>
                  ))}
                </Select>
              )}
              {renderCoverIcon && renderCoverIcon("internalStaff")}
            </FormItem>
          )}
          {this.checkInvoiceRender("issuedReceipt") && (
            <FormItem label={messages("expense-1.key174") /*是否代开*/} {...formItemLayout}>
              {getFieldDecorator("agentTag", {
                rules: [
                  {
                    required: this.checkInvoiceRender("issuedReceipt", 2),
                    message: messages("common.select") /*请选择*/,
                  },
                ],
              })(
                <Select
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  allowClear
                  placeholder={messages("common.select") /*请选择*/}
                  disabled={this.checkInvoiceRender("issuedReceipt", 3)}
                >
                  {agentTagOptions.map((item) => (
                    <Option key={item.key}>{item.value}</Option>
                  ))}
                </Select>
              )}
              {renderCoverIcon && renderCoverIcon("agentTag")}
            </FormItem>
          )}
          {this.checkInvoiceRender("domesticPassengers") && (
            <FormItem label={messages("expense-1.key86") /*国内旅客运输(非港澳台)*/} {...formItemLayout}>
              {getFieldDecorator("domesticPassengers", {
                rules: [
                  {
                    required: this.checkInvoiceRender("domesticPassengers", 2),
                    message: messages("common.select") /*请选择*/,
                  },
                ],
              })(
                <Select
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  allowClear
                  placeholder={messages("common.select") /*请选择*/}
                  disabled={this.checkInvoiceRender("domesticPassengers", 3)}
                >
                  {domesticPassengersOptions.map((item) => (
                    <Option key={item.key}>{item.value}</Option>
                  ))}
                </Select>
              )}
              {renderCoverIcon && renderCoverIcon("domesticPassengers")}
            </FormItem>
          )}
        </div>
        <If value={!isAuditCheck && this.isMoreInfoShow()}>
          <InvoiceMoreInfoEdit
            invoiceInfo={receipt}
            moreInfo={JSON.parse(receipt.moreInfo || "{}")}
            moreInfoLabel={JSON.parse(receipt.moreInfoLabel || "{}")}
            onChange={this.handleMoreInfoChange}
          />
        </If>
        {this.props.profile["invoice.goods.editable.tmp"] && !isAuditCheck && (
          <FormItem labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
            {getFieldDecorator("invoiceGoods", {
              initialValue: this.initInvoiceGoods(),
            })(
              <InvoiceGoods
                taxRates={taxRates}
                disabled={this.checkInvoiceRender("invoiceGoods", 3)}
                currencyCode={this.getFormItemValue("vatInvoiceCurrencyCode")} // 币种
                onChange={this.onInvoiceGoodsChange}
              />
            )}
          </FormItem>
        )}
        <If value={!isAuditCheck}>
          <Button type="primary" loading={checking} htmlType="submit">
            {messages("common.ok") /*确定*/}
          </Button>
          <Button
            onClick={() => (onBack ? onBack() : this.props.close(false))}
            style={{ marginLeft: 8, marginBottom: 16 }}
          >
            {messages("common.back") /*返回*/}
          </Button>
        </If>
      </Form>
    );
  };

  initInvoiceGoods = (invoiceGoods = this.props.receipt.invoiceGoods) => {
    const goods = deepFullCopy(invoiceGoods || []);

    const transfer = (value) => {
      const tr = value - "0";
      return tr ? tr / 100 : 0;
    };

    return goods.map((item) => {
      item.amount = transfer(item.amount);
      item.taxRate = transfer(item.taxRate);
      item.taxPrice = transfer(item.taxPrice);
      item.totalAmount = item.amount + item.taxPrice;
      return item;
    });
  };

  onInvoiceGoodsChange = (value, notForm) => {
    const currencyCode = this.getFormItemValue("vatInvoiceCurrencyCode");

    const nonVATinclusiveAmount = currencyPrecisionCal(
      currencyCode,
      value.reduce((total, item) => total + Number(item.amount), 0)
    );
    const taxAmount = currencyPrecisionCal(
      currencyCode,
      value.reduce((total, item) => total + Number(item.taxPrice), 0)
    );
    const priceTaxAmount = currencyPrecisionCal(
      currencyCode,
      value.reduce((total, item) => total + Number(item.amount) + Number(item.taxPrice), 0)
    );

    const totalAmount = Number(this.getFormItemValue("totalAmount") || 0);

    const nonDeductibleAmount = currencyPrecisionCal(currencyCode, totalAmount - (priceTaxAmount - "0"));

    const taxRate = value[0].taxRate;

    !notForm &&
      this.setFieldsValues({
        nonVATinclusiveAmount,
        taxAmount,
        priceTaxAmount,
        taxRate,
        nonDeductibleAmount,
      });

    return {
      nonVATinclusiveAmount,
      taxAmount,
      priceTaxAmount,
      taxRate,
    };
  };

  handleInvoiceGoods = ({ code, value }) => {
    const currencyCode = this.getFormItemValue("vatInvoiceCurrencyCode");
    const transValue = Number(value) || 0;
    let goods = this.getFormItemValue("invoiceGoods");
    if (goods) {
      goods[0]
        ? goods.splice(1, goods.length)
        : goods.push({
            amount: 0,
            taxPrice: 0,
          });
      goods.forEach((good) => {
        if (code === "nonVATinclusiveAmount") {
          const taxRate = this.getFormItemValue("taxRate");
          const priceTaxAmount = this.getFormItemValue("priceTaxAmount") || 0;
          good.amount = currencyPrecisionCal(currencyCode, transValue);
          good.taxPrice = currencyPrecisionCal(currencyCode, priceTaxAmount - transValue);
          good.taxRate = taxRate;
        }
        if (code === "taxRate") {
          const priceTaxAmount = this.getFormItemValue("priceTaxAmount");
          const amount = priceTaxAmount / (1 + (transValue || 0)); // 不可直接相乘，国家规定算法
          good.taxPrice = currencyPrecisionCal(currencyCode, priceTaxAmount - amount);
          good.amount = currencyPrecisionCal(currencyCode, amount);
          good.taxRate = transValue;
        }

        if (code === "taxAmount") {
          const taxRate = this.getFormItemValue("taxRate");
          const priceTaxAmount = this.getFormItemValue("priceTaxAmount") || 0;
          good.taxPrice = currencyPrecisionCal(currencyCode, transValue);
          good.amount = currencyPrecisionCal(currencyCode, priceTaxAmount - transValue);
          good.taxRate = taxRate;
        }

        if (code === "priceTaxAmount") {
          const taxRate = this.getFormItemValue("taxRate");
          const amount = transValue / (1 + (taxRate || 0));
          good.taxPrice = currencyPrecisionCal(currencyCode, transValue - amount);
          good.amount = currencyPrecisionCal(currencyCode, amount);
          good.taxRate = taxRate;
        }
        good.totalAmount = currencyPrecisionCal(currencyCode, Number(good.amount) + Number(good.taxPrice));
      });
      this.setFieldsValues({ invoiceGoods: goods });
    }
  };

  /**
   * 获取发票提示图片
   */
  getTipImg = async (invoiceTypeNoValue) => {
    // 人工核票页面不需要显示图片
    if (this.props.pageFrom === "auditCheck") {
      return "";
    }
    try {
      const res = await expenseService.getReceiptTipImg(invoiceTypeNoValue);
      return res.data;
    } catch (e) {
      return "";
    }
  };

  /**
   * 不含税金额改变时修改税额
   * @param value
   */
  handleChangeNonVATinclusiveAmount = (value) => {
    const { getFieldsValue, getFieldValue } = this.props.form;
    const currencyCode = this.getFormItemValue("vatInvoiceCurrencyCode");
    const precision = queryCurrencyPrecision(currencyCode);
    const amount = getFieldValue("priceTaxAmount");
    const taxAmount = parseFloat((amount - value).toFixed(precision));
    if (!getFieldsValue().hasOwnProperty("taxAmount")) {
      return;
    }
    if (isNaN(taxAmount)) {
      this.setFieldsValues({ taxAmount: amount });
    } else {
      this.setFieldsValues({ taxAmount });
    }
    this.handleInvoiceGoods({ code: "nonVATinclusiveAmount", value });
  };

  /**
   * 获取发票字段配置
   * @param itemName
   * @param type (number)
   *        1：是否显示（默认值）
   *        2：是否必填
   *        3：是否禁用
   *        4：返回字段的配置值
   */
  checkInvoiceRender = (itemName, type = 1) => {
    const {
      receipt,
      pageFrom,
      isFinance,
      // options: { auditBaseConfig },
    } = this.props;
    const auditBaseConfig = {
      reviewEditSuitable: true,
      reviewEditEnable: true
    }
    const { receiptConfigList, isAuditCheck, invoiceInfo } = this.state;
    console.log({receiptConfigList, isAuditCheck, invoiceInfo})
    let showAttr = false;
    let requiredAttr = false;
    let disabledAttr = isFieldDisabled(receipt, itemName, pageFrom);
    let configValue = "10";
    const fieldItemName = receiptFieldItemMap[itemName] || itemName;
    receiptConfigList &&
      receiptConfigList.map((item) => {
        if (item.valueCode === itemName) {
          configValue = item.value;
          showAttr = item.value !== "10";
          requiredAttr = item.value === "30" || (itemName === "image" && item.value === "40");
          //字段配置不显示，但有值时，显示该字段且不可编辑
          if (
            !isAuditCheck &&
            item.value === "10" &&
            (invoiceInfo[fieldItemName] || invoiceInfo[fieldItemName] === 0)
          ) {
            showAttr = true;
            disabledAttr = true;
          }
        }
      });
    if (isAuditCheck && type === 1) {
      showAttr = this.auditInvoiceItemShow(itemName);
    }
    if (isAuditCheck && type === 3 && !disabledAttr) {
      // disabledAttr = receipt.checkResult === "R_0000" && !receipt.alipayOrWeChat;
      disabledAttr = false;
    }
    // 查验成功且不需要补填信息的 只可编辑部分字段
    if (receipt.checkResult === "R_0000" && isCompleteInvoice(receipt.resultCode)) {
      const enableEditKeys = ["owner", "idCardNo", "personInfo", "internal", "issuedReceipt", "domesticPassengers"];
      if ((!isAuditCheck || (isAuditCheck && !receipt.alipayOrWeChat)) && !enableEditKeys.includes(itemName)) {
        // disabledAttr = true;
        disabledAttr = false;
      }
    }
    const disabled = !isFinance && !(auditBaseConfig.reviewEditSuitable && auditBaseConfig.reviewEditEnable);
    if (isAuditCheck && disabled) {
      // disabledAttr = true;
      disabledAttr = false;
    }
    const returnList = [showAttr, requiredAttr, disabledAttr, configValue];
    return returnList[type - 1];
  };

  //校验财务人工核对发票时，发票字段是否显示
  auditInvoiceItemShow = (itemName) => {
    const { receipt } = this.props;
    const notMatchedColumns = receipt.notMatchedColumns || []; //未匹配的字段
    const fieldItemName = receiptFieldItemMap[itemName] || itemName;
    //字段必填且为空时，需要显示
    if (this.checkInvoiceRender(itemName, 2) && !receipt[fieldItemName] && receipt[fieldItemName] !== 0) {
      return true;
    }
    //字段未匹配时，需要显示
    return !!~notMatchedColumns.indexOf(fieldItemName);
  };

  backInvoiceArea = () => {
    const { beforeReceipt } = this.state;
    this.setState({ currentStep: 0 }, () => {
      this.initReceiptValue(beforeReceipt);
    });
  };

  //日期限制
  disabledDate = (current) => {
    return current && current.valueOf() > Date.now();
  };

  //获取是否需要走修改发票核小费用金额的校验  实际只有审批修改或新增+发票列表编辑会走到这里
  //审批新增发票时entityType为空 其余情况需要校验是关联费用的发票
  getValidAuth = (receiptInfo) => {
    const { receiptOperateScene, createType, currentTab } = this.props;
    return (
      createType === 2 &&
      receiptInfo &&
      ((receiptOperateScene === 2 && currentTab !== "prending_audit") || receiptInfo.entityType === "invoice")
    );
  };

  auditSave = (receipt, shouldRefreshExpenseAmount) => {
    const { onCreate, refreshExpenseAmount, receiptList, receiptOperateScene } = this.props;
    const { resultReceipt, showOCRFlag } = this.state;
    let receiptListCopy = deepFullCopy(receiptList);
    const receiptInfo = receipt || resultReceipt;
    const onDefaultConfirm = () => {
      this.setState({ auditSaving: true, checking: true });
      this.saveReceipt(receiptInfo)
        .then((result) => {
          this.setState({ auditSaving: false, checking: false });
          if (result) {
            onCreate ? onCreate(result, showOCRFlag) : this.props.close(true);
          }
        })
        .catch((e) => {
          this.setState({ auditSaving: false, checking: false });
        });
    };
    //receiptOperateScene: 3 编辑发票  2 费用新增发票
    receiptOperateScene === 3 && receiptListCopy && receiptListCopy.length > 0
      ? (receiptListCopy = receiptListCopy.map((i) => {
          i.id === receiptInfo.id && (i = receiptInfo);
          return i;
        }))
      : receiptList && receiptList.length
      ? receiptListCopy.push(receiptInfo)
      : (receiptListCopy = [receiptInfo]);
    const params = {
      invoiceOID: receiptInfo.invoiceOID,
      receipts: receiptListCopy,
    };
    this.setState({ auditSaving: true, checking: true });
    shouldChangeFeeAutomatic({
      type: receiptOperateScene === 3 ? "EDIT" : "ADD",
      params,
      currentReceipt: receiptInfo,
      validAuth: this.getValidAuth(receiptInfo),
      onConfirm: (reviewResult, autoCalculate) => {
        this._auditSaveReceipt(Object.assign({}, params, { reviewResult, autoCalculate }));
        shouldRefreshExpenseAmount && refreshExpenseAmount && refreshExpenseAmount(reviewResult);
      },
      onCancel: () => this.setState({ auditSaving: false, checking: false }),
      onDefaultConfirm,
    });
  };

  //财务修改发票信息自动核定费用金额
  _auditSaveReceipt = (params) => {
    const { onCreate } = this.props;
    const { showOCRFlag } = this.state;
    const onSuccess = (res) => {
      if (res) {
        onCreate
          ? onCreate(res.data.rows && res.data.rows[0] ? res.data.rows[0] : params.receipts[0], showOCRFlag)
          : this.props.close(true);
      }
    };
    auditSaveReceipt(params, onSuccess, this).finally(() => this.setState({ auditSaving: false, checking: false }));
  };
  // 显示标签信息
  showMessage = (item) => {
    if (!item.name) {
      return <div>{item.toast && item.toast.split("&#13;").map((item) => <div>{item}</div>)}</div>;
    }
    if (!item.toast) {
      return item.name;
    }
    return (
      <div>
        {item.name}：
        {item.toast &&
          item.toast.split("&#13;").map((item, index) => {
            if (index === 0) return <span>{item}</span>;
            return <div>{item}</div>;
          })}
      </div>
    );
  };

  render() {
    const {
      loading,
      currentStep,
      resultReceipt,
      canSubmit,
      auditSaving,
      showOCRFlag,
      isAuditCheck,
      cacheReceiptLabels,
    } = this.state;
    const { onCreate, receipt, invoiceBagId, expenseReportId, fromVICP } = this.props;
    return (
      <div className={`create-invoice ${isAuditCheck ? "audit-check-invoice" : ""}`}>
        {currentStep === 0 && <div className="invoice-input-notes-container" />}
        {currentStep === 0 ? (
          <Spin spinning={loading}>
            {!isAuditCheck && cacheReceiptLabels.filter((item) => item.type !== "HAND_RECODE_RECEIPT").length > 0 && (
              <div className="tip-wrap">
                {/* 非普通标签单独一行显示*/}
                {cacheReceiptLabels
                  .filter((item) => item.level !== "INFO")
                  .map((item) => (
                    <Alert
                      message={this.showMessage(item)}
                      key={item.name}
                      type={item.level === "ERROR" ? "error" : "info"}
                      showIcon
                    />
                  ))}
                {/* 普通标签拼接成一行显示*/}
                {cacheReceiptLabels.filter((item) => item.level === "INFO" && item.type !== "HAND_RECODE_RECEIPT")
                  .length > 0 && (
                  <Alert
                    message={cacheReceiptLabels
                      .filter((item) => item.level === "INFO" && item.type !== "HAND_RECODE_RECEIPT")
                      .map((item) => item.name)
                      .join("/")}
                    type="info"
                    showIcon
                  />
                )}
              </div>
            )}
            {this.renderInvoiceArea()}
          </Spin>
        ) : (
          <div style={{ paddingTop: 20 }}>
            <Invoice invoiceList={[resultReceipt]} canExpense={false} />
            {canSubmit && (
              <div style={{ textAlign: "center", marginBottom: 30 }}>
                <a
                  onClick={() => {
                    onCreate ? onCreate(receipt, showOCRFlag) : this.props.close(true);
                  }}
                  style={{ fontSize: 16 }}
                >
                  {messages("expense-1.key175") /*生成费用*/}&nbsp;&nbsp;
                  <Icon type="right-circle-o" />
                </a>
              </div>
            )}
            {!canSubmit && (
              <div style={{ textAlign: "center", marginBottom: 30 }}>
                <a onClick={this.backInvoiceArea} style={{ fontSize: 16 }}>
                  <Icon type="left-circle-o" />
                  &nbsp;&nbsp;{messages("common.back") /*返回*/}
                </a>
                <span style={{ marginLeft: 40 }}>
                  {(invoiceBagId || expenseReportId || fromVICP) &&
                    (auditSaving ? (
                      <Spin />
                    ) : (
                      <a onClick={(e) => this.auditSave()} style={{ fontSize: 16 }}>
                        <Icon type="check-circle-o" />
                        &nbsp;&nbsp;{messages("common.save") /*保存*/}
                      </a>
                    ))}
                </span>
              </div>
            )}
          </div>
        )}
      </div>
    );
  }
}

CreateInvoice.propTypes = {
  onCreate: React.PropTypes.func,
  onBack: React.PropTypes.func,
  createType: React.PropTypes.number,
  receipt: React.PropTypes.any,
  invoiceOID: React.PropTypes.any, //费用oid可传空
  currencyList: React.PropTypes.array, //费用币种list
  invoiceUserFp: React.PropTypes.object, //申请人费用FP
  receiptOperateScene: React.PropTypes.number, //发票操作场景：1.发票创建费用；2.费用新增发票；3.费用编辑发票
  receiptList: React.PropTypes.array, //添加到费用里面的发票
  userOID: React.PropTypes.string, //用户发票
  currency: React.PropTypes.string,
  pageFrom: React.PropTypes.string,
  currentTab: React.PropTypes.string, //当前所在的Tab标志
};

CreateInvoice.defaultProps = {
  createType: 1, //1.是员工//2是财务
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    documentaryCompany: state.login.documentaryCompany,
    language: state.main.language,
    options: state.login.options,
    profile: state.login.profile,
  };
}

const WrappedCreateInvoice = Form.create()(CreateInvoice);

export default connect(mapStateToProps)(WrappedCreateInvoice);
